import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { FormProps } from 'antd';
import React from 'react';
import { Form, Input, Button, Steps, DatePicker, message } from 'antd';
import type { Dayjs } from 'dayjs';
import axios from 'axios';

const Add: React.FC = () => {
    const navigate = useNavigate();
    const [current, setCurrent] = useState(0);
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);

    type FieldType = {
        name?: string;
        dzs?: number;
        time?: Dayjs;
        bfs?: number;
    };

    const onFinish1: FormProps<FieldType>['onFinish'] = async (values) => {
        try {
            const list = localStorage.setItem('list', JSON.stringify(values))
            // 格式化提交数据
            console.log(list);

            setCurrent(current + 1);
            // 提交到后端API

        } catch (error) {
            console.error('提交失败:', error);
            message.error('提交失败，请重试');
        } finally {
            setLoading(false);
        }

        // 验证当前步骤表单
    };

    const prev = () => {
        setCurrent(current - 1);
    };

    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        try {
            setLoading(true);
            // 格式化提交数据
            const list = localStorage.getItem('list')
            const data = JSON.parse(list as string)
            console.log(data);
            
            const submitData = {
                ...values,
                time: values.time?.format('YYYY-MM-DD'),
                dzs: data.dzs,
                bfs: values.bfs,
                name:data.name
            };

            // 提交到后端API
            await axios.post('http://localhost:3000/add', submitData);
            message.success('数据添加成功！');
            setCurrent(2); // 跳转到完成页
        } catch (error) {
            console.error('提交失败:', error);
            message.error('提交失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    const steps = [
        { title: '基础信息', description: '填写基本数据' },
        { title: '详细信息', description: '完善详细内容' },
        { title: '完成', description: '添加成功' },
    ];

    return (
        <div style={{ maxWidth: 800, margin: '0 auto', padding: '20px' }}>
            <Steps current={current} items={steps} />
            <div style={{ marginTop: 20 }}>
                {current === 0 && (
                    <div>
                        <Form

                            form={form}
                            name="add_form"
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 16 }}
                            onFinish={onFinish1}
                            autoComplete="off"
                        >
                            {/* 步骤1：基础信息 */}

                            <Form.Item<FieldType>
                                label="名称"
                                name="name"
                                rules={[{ required: true, message: '请输入名称' }]}
                            >
                                <Input placeholder="请输入名称" />
                            </Form.Item>

                            <Form.Item<FieldType>
                                label="点赞数"
                                name="dzs"
                                rules={[
                                    { required: true, message: '请输入点赞数' },
                        
                                ]}
                            >
                                <Input placeholder="请输入点赞数" />
                            </Form.Item>

                            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                <Button type="primary" htmlType="submit" >
                                    下一步
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                )}

                {/* 步骤2：详细信息 */}
                {current === 1 && (
                    <div>
                        <Form

                            form={form}
                            name="add_form"
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 16 }}
                            onFinish={onFinish}
                            autoComplete="off"
                        >

                            <Form.Item<FieldType>
                                label="播放数"
                                name="bfs"
                                rules={[
                                    { required: true, message: '请输入播放数' },

                                ]}
                            >
                                <Input placeholder="请输入播放数" />
                            </Form.Item>

                            <Form.Item<FieldType>
                                label="历史时间"
                                name="time"
                                rules={[{ required: true, message: '请选择时间' }]}
                            >
                                <DatePicker placeholder="请选择时间" style={{ width: '100%' }} />
                            </Form.Item>

                            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                <Button style={{ marginRight: 8 }} onClick={prev}>
                                    上一步
                                </Button>
                                <Button type="primary" htmlType="submit" loading={loading}>
                                    提交
                                </Button>
                            </Form.Item>
                        </Form>

                    </div>
                )}
                {/* 步骤3：完成页 */}
                {current === 2 && (
                    <div style={{ textAlign: 'center', padding: '50px 0' }}>
                        <h2>数据添加成功！</h2>
                        <div style={{ marginTop: 20 }}>
                            <Button onClick={() => navigate('/home3')}>返回列表</Button>
                            <Button type="primary" onClick={() => navigate('/add')}>
                                继续添加
                            </Button>
                        </div>
                    </div>

                )}

            </div >
        </div >
    );
};

export default Add;